var ImEvent = {
	RESP_CONTACT : "RESP_CONTACT", // 返回联系人列表
	RESP_RECMSG : "RESP_RECMSG", // 接收消息
	RESP_CHATHIS : "RESP_CHATHIS",// 返回聊天记录
	RESP_NEWMSG : "RESP_NEWMSG",// 返回新消息提示
	REQ_CONTACT : "REQ_CONTACT", // 请求联系人列表
	REQ_CHATHIS : "REQ_CHATHIS", // 请求聊天历史
	REQ_SENDMSG : "REQ_SENDMSG", // 请求发送消息
	REQ_NEWCHAT : "REQ_NEWCHAT",// 请求创建新的
	REQ_UPDATEREAD : "REQ_UPDATEREAD" // 请求更新消息为已读
};

ImEvent.MessageSparator = "|@|";
/** 获取请求联系人列表 */
ImEvent.getReqContact = function() {
	return ImEvent.REQ_CONTACT;
};
/** 获取请求发送消息请求 */
ImEvent.getReqSendMsg = function(sendUserId, message) {
	return ImEvent.REQ_SENDMSG + ImEvent.MessageSparator + sendUserId
			+ ImEvent.MessageSparator + message;
};
/** 获取请求聊天历史请求 */
ImEvent.getReqChatHis = function(relUserId, lastMessageId) {
	return ImEvent.REQ_CHATHIS + ImEvent.MessageSparator + relUserId
			+ ImEvent.MessageSparator + lastMessageId;
};
/** 获取新的聊天会话请求 */
ImEvent.getNewChat = function(relUserId) {
	return ImEvent.REQ_NEWCHAT + ImEvent.MessageSparator + relUserId;
};
/** 获取更新已读请求 */
ImEvent.getReqUpdateRead = function(relUserId, messageIds) {
	return ImEvent.REQ_UPDATEREAD + ImEvent.MessageSparator + relUserId
			+ ImEvent.MessageSparator + messageIds;
};

var Chat = {};

Chat.imUserId = null;

Chat.socket = null;

Chat.chatUserId = null;

Chat.connect = (function(host) {
	if ('WebSocket' in window) {
		Chat.socket = new WebSocket(host);
	} else if ('MozWebSocket' in window) {
		Chat.socket = new MozWebSocket(host);
	} else {

		return;
	}

	Chat.socket.onopen = function() {

		document.getElementById('editContent').onkeydown = function(event) {
			if (event.keyCode == 13) {
				Chat.sendMessage();
			}
		};

		var chatImUserId = jQuery.url.param("chatImUserId");
		if (chatImUserId)
			Chat.socket.send(ImEvent.getNewChat(chatImUserId));
	};

	Chat.socket.onclose = function() {
		document.getElementById('chat').onkeydown = null;
	};

	Chat.socket.onmessage = function(message) {
		MessageControl.processMessage(message.data);
	};
});

Chat.initialize = function() {
	if (window.location.protocol == 'http:') {
		Chat.connect('ws://' + window.location.host + '/ewingdoor/im/chat');
	} else {
		Chat.connect('wss://' + window.location.host + '/ewingdoor/im/chat');
	}
};

Chat.sendMessage = (function() {
	var message = document.getElementById('editContent').value;
	var sendUserId = Chat.chatUserId;
	if (message != '' && sendUserId) {
		var sendMsg = ImEvent.getReqSendMsg(sendUserId, message);
		Chat.socket.send(sendMsg);
		document.getElementById('editContent').value = '';
	}
});

Chat.askContactList = function() {
	Chat.socket.send(ImEvent.getReqContact());
};

Chat.askChatHistory = (function() {
	var relation = ImUserInfo.getImRelationInfo(Chat.chatUserId);
	var lastMessageId = relation && relation.lastMessageId ? relation.lastMessageId
			: "0";
	console.log("askChatHistory:" + Chat.chatUserId + ",lastMessageId:"
			+ lastMessageId);
	Chat.socket.send(ImEvent.getReqChatHis(Chat.chatUserId, lastMessageId));
});

Chat.update2Read = function(relUserId, messageIds) {
	Chat.socket.send(ImEvent.getReqUpdateRead(relUserId, messageIds));
};

var MessageControl = {};

MessageControl.processMessage = function(messageWapperStr) {
	var messageWapper = $.parseJSON(messageWapperStr);
	var imEvent = messageWapper.imEvent;
	if (imEvent == ImEvent.RESP_CONTACT) {
		ImUserInfo.initContactListPanel(messageWapper.result);
	} else if (imEvent == ImEvent.RESP_CHATHIS) {
		ImUserInfo.renderChatHistory(messageWapper.result);
	} else if (imEvent == ImEvent.RESP_RECMSG) {
		ImUserInfo.renderChatHistory(messageWapper.result);
	} else if (imEvent == ImEvent.RESP_NEWMSG) {
		ImUserInfo.changeMessageTip(messageWapper.result);
	}
};

var ImUserInfo = {};

ImUserInfo.contactList = null;

/** 获取联系人信息 */
ImUserInfo.getImRelationInfo = function(imUserId) {
	if (ImUserInfo.contactList) {
		for (var i = 0; i < ImUserInfo.contactList.length; i++) {
			if (ImUserInfo.contactList[i].userInfo.imUserId == imUserId) {
				return ImUserInfo.contactList[i];
			}
		}
	}
};
/** 检查目前的本地联系人是否有指定的用户 */
ImUserInfo.existContact = function(imUserId) {
	if (ImUserInfo.contactList) {
		for (var i = 0; i < ImUserInfo.contactList.length; i++) {
			if (ImUserInfo.contactList[i].userInfo.imUserId == imUserId) {
				return true;
			}
		}
	}
	return false;
};
/** 根据聊天记录更新关联联系人的最后消息ID，以及更新消息的状态为已读 */
ImUserInfo.updateLastMessageId = function(chatHistoryList) {
	console.log("updateLastMessage chatHistoryList:" + chatHistoryList);
	if (!chatHistoryList || chatHistoryList.length == 0)
		return;
	var relImUserId = chatHistoryList[0].relImUserId;
	var lastMessageId = chatHistoryList[chatHistoryList.length - 1].messageId;
	if (ImUserInfo.contactList) {
		for (var i = 0; i < ImUserInfo.contactList.length; i++) {
			if (ImUserInfo.contactList[i].userInfo.imUserId == relImUserId) {
				console.log("updateLastMessage relImUserId:" + relImUserId
						+ " messageId:" + lastMessageId);
				ImUserInfo.contactList[i].lastMessageId = lastMessageId;
				break;
			}
		}
	}
	var updateMessageIds = "";
	for (var i = 0; i < chatHistoryList.length; i++) {
		// 未读且为接收类型，需要拼接消息ID
		if (chatHistoryList[i].readStatus == 0
				&& chatHistoryList[i].messageType == 2) {
			updateMessageIds += chatHistoryList[i].messageId;
		}
		if (i < chatHistoryList.length - 1)
			updateMessageIds += ",";
	}
	if (updateMessageIds)
		Chat.update2Read(relImUserId, updateMessageIds);
};
/** 初始化联系人列表 */
ImUserInfo.initContactListPanel = function(contactList) {
	if (!contactList)
		return; 
	ImUserInfo.storeContactList(contactList);
	$('#contact_panel').html("");
	$('#contact_panel').loadTemplate($("#contactLi"), ImUserInfo.contactList);
	PanelEvent.bindContactTouch(); 
	if (contactList[0]) {
		Chat.chatUserId = contactList[0].userInfo.imUserId;
		var allContactLi = $(".contactLi");
		// PanelEvent.clickContacter(Chat.chatUserId);
		$(allContactLi[0]).trigger("click");
	}
};
/** 渲染聊天记录 */
ImUserInfo.renderChatHistory = function(chatHistoryList) {
	if (!chatHistoryList || chatHistoryList.length == 0)
		return;

	storeChatHistory(chatHistoryList);

	for (var i = 0; i < chatHistoryList.length; i++) {
		var chatContent = chatHistoryList[i];
		console.log('chat content:' + chatContent.content
				+ " ,messageTypeClass:" + chatContent.messageTypeClass
				+ " sendImUserId:" + chatContent.sendImUserId + ",revImUserId:"
				+ chatContent.revImUserId);
	}

	var imUserId = chatHistoryList[0].relImUserId;
	if (Chat.imUserId == imUserId) {
		ImUserInfo.updateLastMessageId(chatHistoryList);
		$('#chat_hidden_content').loadTemplate($("#chatHistory"),
				chatHistoryList);
		$('#chat_main_panenl').append($('#chat_hidden_content').html());
		var obj = document.getElementById("message_content");
		obj.scrollTop = obj.scrollHeight;
	}
};

ImUserInfo.changeMessageTip = function(messageTip) {
	if (!messageTip)
		return;
	var notReadTotal = messageTip.notReadTotal;
	var imUserIds = messageTip.imUserIds;
	$('#notReadTotal').html(notReadTotal);

	for (var i = 0; i < imUserIds.length; i++) {
		if (!ImUserInfo.existContact(imUserIds[i])) {
			//Chat.chatUserId = imUserIds;
			Chat.askContactList();
			//Chat.askChatHistory();
			break;
		}
		if (imUserIds[i] == Chat.chatUserId) {
			Chat.askChatHistory();
			break;
		}
	}
};
/**
 * 保存聊天记录到本地
 */
ImUserInfo.storeChatHistory = function(chatHistoryList) {
	if (!chatHistoryList || chatHistoryList.length == 0)
		return;

	var imUserId = chatHistoryList[0].relImUserId;
	if (ImUserInfo.contactList) {
		for (var i = 0; i < ImUserInfo.contactList.length; i++) {
			if (ImUserInfo.contactList[i].userInfo.imUserId == imUserId) {
				if (!ImUserInfo.contactList[i].chatRecords) {
					ImUserInfo.contactList[i].chatRecords = chatHistoryList;
				} else {
					for (var j = 0; j < chatHistoryList.length; j++) {
						ImUserInfo.contactList[i].chatRecords
								.push(chatHistoryList[j]);
					}
				}
				break;
			}
		}
	}
};
/**
 * 获取指定联系人的聊天记录
 */
ImUserInfo.getChatHistory = function(imUserId){
	if (ImUserInfo.contactList) {
		for (var i = 0; i < ImUserInfo.contactList.length; i++) {
			if (ImUserInfo.contactList[i].userInfo.imUserId == imUserId) { 
					return	ImUserInfo.contactList[i].chatRecords; 
			}
		}
	}
};

ImUserInfo.storeContactList = function(contactList) {
	if (ImUserInfo.contactList) {

		for (var i = 0; i < contactList.length; i++) {
			var exist = false;
			for (var i = 0; i < ImUserInfo.contactList.length; i++) {
				if (ImUserInfo.contactList[i].userInfo.imUserId == contactList[i].userInfo.imUserId) {
					exist = true;
					break;
				}
			}
			if (!exist) {
				ImUserInfo.contactList.push(contactList[i]);
			}
		}

	} else {
		ImUserInfo.contactList = contactList;
	}
};

/** 切换到指定联系人的聊天记录 */
ImUserInfo.switchChatWindow = function(imUserId) { 
	if (!imUserId)
		return;
	var chatHistoryList = ImUserInfo.getChatHistory(imUserId);
	$('#chat_hidden_content').loadTemplate($("#chatHistory"),
			chatHistoryList);
	$('#chat_main_panenl').html($('#chat_hidden_content').html());
	var obj = document.getElementById("message_content");
	obj.scrollTop = obj.scrollHeight;
};

var PanelEvent = {};

PanelEvent.bindContactTouch = function() {
	$(".contactLi").bind("click", function(e) {
		PanelEvent.clickContacter($(this).attr("imUserId"));
		Chat.askChatHistory();
	});
};

PanelEvent.clickContacter = function(imUserId) { 
	Chat.chatUserId = imUserId;
	ImUserInfo.switchChatWindow(Chat.chatUserId);
	var relationInfo = ImUserInfo.getImRelationInfo(Chat.chatUserId);
	$("#nickname_text").html(relationInfo.userInfo.name);
	$("#chat_title").html(relationInfo.userInfo.name);
};

PanelEvent.bindSendMessage = function() {
	$(".send_btn").bind("click", function(e) {
		Chat.sendMessage();
	});
};

function login() {
	var imUserId = jQuery.url.param("imUserId");
	var userName = jQuery.url.param("userName");
	var loginUrl = "http://" + window.location.host
			+ "/ewingdoor/LoginTest?imUserId=" + imUserId + "&userName="
			+ userName;
	$.ajax({
		url : loginUrl,
		type : 'POST',
		async : false,
		dataType : 'html',
		success : function() {
			Chat.initialize();
			Chat.imUserId = imUserId;
			PanelEvent.bindSendMessage();
		}
	});
}

login();

document.addEventListener("DOMContentLoaded", function() {
	// Remove elements with "noscript" class - <noscript> is not allowed in
	// XHTML
	var noscripts = document.getElementsByClassName("noscript");
	for (var i = 0; i < noscripts.length; i++) {
		noscripts[i].parentNode.removeChild(noscripts[i]);
	}
}, false);
